package controller

import (
	"fmt"
	"gin-shop-admin/models"
	"gin-shop-admin/repository"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"strconv"
)

func GetGoodsList(c *gin.Context)  {
	query := c.Query("query")
	pageNum := c.Query("pagenum")
	pageSize := c.Query("pagesize")
	goods, total, err := repository.GetGoodsList(query, pageNum, pageSize)
	if err != nil {
		c.JSON(201, gin.H{"msg": err, "goods": nil, "total": total})
	}else{
		c.JSON(http.StatusOK, gin.H{"total": total, "goods": goods, "msg": "success"})
	}
	return
}

func DeleteOneGoods(c *gin.Context)  {
	id, ok := c.Params.Get("id")
	good_id, err := strconv.Atoi(id)
	if !ok || err != nil{
		log.Println(err)
		c.JSON(201, gin.H{"msg": "参数接收有误"})
		return
	}
	err = repository.DeleteOneGoods(good_id)
	if err != nil {
		c.JSON(202, gin.H{"msg": err})
	}else {
		c.JSON(http.StatusOK, gin.H{"msg": "删除成功"})
	}
	return
}

func AddOneGoods(c *gin.Context)  {
	var good_form models.GoodsForm
	err := c.BindJSON(&good_form)
	if err!= nil {
		fmt.Println(err)
		c.JSON(201, gin.H{"msg": err})
		return
	}
	err = repository.AddOneGoods(good_form)
	if err != nil {
		c.JSON(202, gin.H{"msg": err})
	}else {
		c.JSON(http.StatusOK, gin.H{"msg":"创建成功"})
	}
	return
}